<template>
  <div class="vue-container">
    <el-dialog
      ref="maxDialog"
      v-drag
      :title="title"
      :visible.sync="dialogVisible"
      :width="width"
      @closed="closedDialog"
    >
      <el-descriptions v-loading="loading" :size="size" :column="column" :border="border">
        <template v-for="(item, index) in fields">
          <el-descriptions-item v-if="!item.slot && !item.hidden" :key="index" :label="item.label" :span="item.span || 1">
            {{ ruleForm[item.key] }}
          </el-descriptions-item>
          <template v-else-if="!item.hidden">
            <el-descriptions-item :key="index" :label="item.label" :span="item.span">
              <slot :name="item.slot" :rows="ruleForm" :item="item" />
            </el-descriptions-item>
          </template>
        </template>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button v-loading="loading" :size="size" @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'CommonDetail',
  props: {
    width: {
      type: String,
      default: '800px'
    },
    title: {
      type: String,
      default: '详情'
    },
    // 初始化表单对象
    createForm: {
      type: Object,
      default: () => {}
    },
    column: {
      type: Number,
      default: 3
    },
    border: {
      type: Boolean,
      default: true
    },
    // 字段数组
    fields: {
      type: Array,
      default: () => []
    },
    // 打开后事件
    customOpenFun: {
      type: Function,
      default: function() { }
    }
  },
  data() {
    return {
      ruleForm: {},
      dialogVisible: false,
      loading: false
    }
  },
  computed: {
    size() {
      return this.$store.state.app.size
    },
    funs() {
      return this.$store.state.settings.funs
    }
  },
  methods: {
    // 弹出窗口加载
    openDialog(rows) {
      this.loading = true
      this.funs['detail'](rows.id).then(res => {
        this.ruleForm = { ...this.createForm, ...res.data }
        if (this.customOpenFun) this.customOpenFun(this)
        this.fields.forEach(row => {
          if (!((row.key || row.slot) in this.ruleForm)) row.hidden = true
          else row.hidden = false
        })
        this.dialogVisible = true
      }).finally(() => {
        this.loading = false
      })
    },
    // 弹窗关闭动画结束触发
    closedDialog() {
      // 表单校验重置
      this.ruleForm = this.createForm
    }
  }
}
</script>
